set(prj_name nginxd)

# Path to the Nginx source code
set(NGINX_SOURCE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/nginx-1.14.0)

# add WITH_SSL option, default is ON
option(WITH_SSL "Build Nginx with SSL support" ON)

include(ExternalProject)

if(WITH_SSL)
    set(NGINX_CONFIGURE_ARGS --prefix=${CMAKE_BINARY_DIR}/output/nginxd --with-http_ssl_module)
    message(STATUS "Building Nginx with SSL support")
else()
    set(NGINX_CONFIGURE_ARGS --prefix=${CMAKE_BINARY_DIR}/output/nginxd)
    message(STATUS "Building Nginx without SSL support")
endif()

ExternalProject_Add(
        nginxall
        SOURCE_DIR ${NGINX_SOURCE_PATH}
        CONFIGURE_COMMAND cd ${NGINX_SOURCE_PATH} && ./configure ${NGINX_CONFIGURE_ARGS}
        BUILD_COMMAND make -C ${NGINX_SOURCE_PATH}
        INSTALL_COMMAND make install -C ${NGINX_SOURCE_PATH}
)

add_custom_target(nginxd ALL
    COMMENT "Build nginxd target Finish")


add_custom_target(nginx_copy
    COMMAND cp -a html/* $(CMAKE_BINARY_DIR)/output/nginxd/html
    COMMAND cp -a conf/nginx.conf $(CMAKE_BINARY_DIR)/output/nginxd/conf/nginx.conf
    COMMAND cp -a conf/nginx.conf $(CMAKE_BINARY_DIR)/output/nginxd/conf/nginx.conf.default
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/nginx-1.14.0)

ADD_DEPENDENCIES(nginx_copy nginxall)
ADD_DEPENDENCIES(nginxd nginx_copy)

#configure_file(
#    "${CMAKE_CURRENT_SOURCE_DIR}/cmake_nginx.cmake.in"
#    "${CMAKE_CURRENT_BINARY_DIR}/cmake_nginx.cmake"
#    IMMEDIATE @ONLY)

#add_custom_target(nginxd ALL
#    COMMENT "Build nginxd target Finish")

#add_custom_target(cmake_nginx
#COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_nginx.cmake)

#add_custom_target(nginx
#    COMMAND ${CMAKE_MAKE_PROGRAM}
#    COMMAND make install
#    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/nginx-1.14.0)

#ADD_DEPENDENCIES(nginx cmake_nginx)
#ADD_DEPENDENCIES(nginxd nginx)

install(DIRECTORY ${CMAKE_BINARY_DIR}/output/nginxd DESTINATION bin USE_SOURCE_PERMISSIONS)
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/conf/cert  DESTINATION bin/nginxd/conf/ USE_SOURCE_PERMISSIONS)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/conf/nginx_with_ssl.conf DESTINATION bin/nginxd/conf/ )